/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.ac.cam.ccn.sac.modules.audio.message;

import uk.ac.cam.ccn.sac.modules.audio.message.AudioMessage;
import uk.ac.cam.ccn.sac.modules.audio.PlayThread;
import uk.ac.cam.ccn.sac.modules.audio.CaptureThread;
import uk.ac.cam.ccn.sac.net.CCNNet;
import uk.ac.cam.ccn.sac.net.CCNNet.AudioCallBack;

/**
 *
 * @author Thomas
 */
public class AudioChatManager implements AudioCallBack{
    private static final AudioChatManager instance = new AudioChatManager();
    private CaptureThread ct = null;
    private PlayThread pt = null;
    
    public static AudioChatManager getInstance(){
        return instance;
    }
    
    private AudioChatManager(){
    }
    
    public void startRecord(){
        // already recording
        if(ct!=null){
            ct.stopRecord();
        }
        
        ct = new CaptureThread();
        ct.start();
    }
    
    public void stopRecord(){
        // is there a record started
        if(ct!=null)
            ct.stopRecord();
    }
    
    // send the last record
    public void send(){
        if(ct!=null){
            ct.stopRecord();
            byte[] record = ct.getRecord();
            ct = null;
            try{
                CCNNet.getInstance().sendAudio(new AudioMessage(record));
            }catch(Exception e){}
        }
    }
    
    public void playRecorded(){
        if(ct!=null){
            ct.stopRecord();
            byte[] record = ct.getRecord();
            ct = null;
            play(record);
        }
    }
    
    public void play(byte[] record){
        // if already playing stop it
        if(pt!=null)
            pt.stopPlay();
        
        pt = new PlayThread(record);
        pt.start();
    }
    
    public void stopPlay(){
        if(pt!=null)
            pt.stopPlay();
    }

    @Override
    public void audioReceived(AudioMessage message) {
        this.play(message.getAudio());
    }
}
